//
//  FindClassifyDetailViewController.m
//  Everest
//
//  Created by 李其昌 on 14/12/17.
//  Copyright (c) 2014年 ThreeL. All rights reserved.
//

#import "FindClassifyDetailViewController.h"
#import "ClassifyDetailCell.h"
#import "NetHandler.h"
#import "ClassifyDetail.h"
#import "MJRefresh.h"
#import "AlbumViewController.h"
#import "UIColor+AddColor.h"

#define PAGE_NUMBER 1


@interface FindClassifyDetailViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *arr;       // 存储对象的数组
@property (nonatomic, assign) int i;
@property (nonatomic, retain) UISegmentedControl *segmented;
@property (nonatomic, retain) NSString *str;

@end

@implementation FindClassifyDetailViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        self.arr = [NSMutableArray array];
        self.i = 1;
        
        NSNotificationCenter *fication = [NSNotificationCenter defaultCenter];
        [fication addObserver:self selector:@selector(ficationAction:) name:@"findclassify" object:nil];
    }
    return self;
}

- (void)ficationAction:(NSNotification *)noti
{
    self.collect = @"YES";
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.translucent = YES;
    [self handleData];
}

- (void)handleData
{
    
    
    if ([self.classify.name isEqualToString:@"all"] && ([self.classify.tname isEqualToString:@"全部"] || [self.classify.tname isEqualToString:@"推荐专辑"])) {
        
        self.classify.tname = @"";
        
    }
        
    if (self.segmented.selectedSegmentIndex == 0) {
        
        self.str = @"hot";
        
    } else if (self.segmented.selectedSegmentIndex == 1) {
        
        self.str = @"recent";
        
    } else if (self.segmented.selectedSegmentIndex == 2) {
        
        self.str = @"classic";
        
    }
    
   NSString  *strs = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=%@&condition=%@&device=iPhone&page=1&per_page=20&status=0&tag_name=%@", self.classify.name, self.str, self.classify.tname];
//    NSLog(@"%@", strs);
    [NetHandler getDataWithUrl:strs completion:^(NSData *data) {
        
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSArray *array = [resultDic objectForKey:@"list"];
        if (self.arr.count != 0) {
            [self.arr removeAllObjects];
        }
//        NSLog(@"%ld", self.arr.count);
        for (NSDictionary *dic in array) {
            
            ClassifyDetail *classifyData  = [[ClassifyDetail alloc] initWithDictionary:dic];
            
            [self.arr addObject:classifyData];
            
            [classifyData release];
        }
//        NSLog(@"%ld", self.arr.count);
        [self.tableView reloadData];
//        NSLog(@"%@", self.arr);
    }];
    
}

- (void)dealloc
{
    [_collect release];
    [_arr release];
    [_tableView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = self.classify.tname;
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.contentInset = UIEdgeInsetsMake(25, 0, -49, 0);
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    [self.tableView registerClass:[ClassifyDetailCell class] forCellReuseIdentifier:@"reuse"];
    // 根据tableView的偏移量 判断是否刷新
    if (self.tableView.contentOffset.y > - 64) {
        [self setupRefresh];
    }
    
    NSArray *segArr = [NSArray arrayWithObjects:@"最火", @"最近更新", @"经典", nil];
    
    self.segmented = [[UISegmentedControl alloc] initWithItems:segArr];
    self.segmented.frame = CGRectMake(0, 64, self.view.bounds.size.width, 30);
    self.segmented.backgroundColor = [UIColor whiteColor];
    self.segmented.tintColor = [UIColor kuGouColor];
    self.segmented.selectedSegmentIndex = 0;
    
    [self.segmented addTarget:self action:@selector(segmentedAction:) forControlEvents:UIControlEventValueChanged];
    
    [self.view addSubview:self.segmented];
    [_segmented release];
    
    
}

// cell 的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ClassifyDetail *classifyDetail = [self.arr objectAtIndex:indexPath.row];
    
    AlbumViewController *albumVC = [[AlbumViewController alloc] init];
    
    albumVC.classifyDetail = classifyDetail;
    albumVC.collect = self.collect;
    
    [self.navigationController pushViewController:albumVC animated:YES];
    
    [albumVC release];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.arr count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ClassifyDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    
    ClassifyDetail *classifyData = [self.arr objectAtIndex:indexPath.row];
    
    cell.classify = classifyData;
    
    return cell;
    
}

- (void)segmentedAction:(UISegmentedControl *)seg
{
    // segmented 的方法
    
    // segmented 根据下标 调用不同方法
    
    [self handleData];

    [self setupRefresh];
}

- (void)setupRefresh
{
    //    NSLog(@"进入了setupRefresh");
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //进入刷新状态(一进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}



#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    
    //1. 在这调用请求网络数据方法（刷新数据）
    
    [self handleData];
    
    
    //2. 2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
}

//   进入加载状态
- (void)footerRereshing
{
    //1. 拼接口等操作
    // 请求加载数据
    [self lengDate];
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView reloadData];
        [self.tableView footerEndRefreshing];
    });
}
// 上拉加载 数据处理方法
- (void)lengDate
{
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=%@&condition=hot&device=iPhone&page=%d&per_page=20&status=0&tag_name=%@", self.classify.name, PAGE_NUMBER + self.i, self.classify.tname];
    
    [NetHandler getDataWithUrl:str completion:^(NSData *data) {
        
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSArray *array = [resultDic objectForKey:@"list"];
        
        for (NSDictionary *dic in array) {
            
            ClassifyDetail *classifyData  = [[ClassifyDetail alloc] initWithDictionary:dic];
            
            [self.arr addObject:classifyData];
            
            [classifyData release];
        }
        
    }];
    self.i++;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
